import 'dart:async';
import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/match/detail/lq_match_detail_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/basketball_api.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/ads_label.dart';

class LqDetailOutsWidget extends StatefulWidget {
  const LqDetailOutsWidget(
      {super.key, required this.id, this.haveTopData = false});

  final int id;
  final bool haveTopData;

  @override
  State<LqDetailOutsWidget> createState() => _LqDetailOutsWidgetState();
}

class _LqDetailOutsWidgetState extends State<LqDetailOutsWidget> {
  LqMatchDetailEntity? detail;
  int liveCount = 30;
  int periodNum = 0;
  List get lives => detail?.appMatchTlives?[periodNum - 1].data ?? [];
  bool get nomore => liveCount > lives.length;

  FutureOr getMatchDetail() async {
    final response = await BasketballApi.lqMatchDetail(widget.id);
    try {
      detail = LqMatchDetailEntity.fromJson(response.data['d']);
      if ((detail?.appMatchTlives?.length ?? 0) > 0) {
        periodNum = detail?.appMatchTlives?.length ?? 0;
      }
      update();
    } catch (err) {
      log("篮球获取比赛详情出错");
      log("$err");
    }
  }

  @override
  void initState() {
    getMatchDetail();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.builder(
      onRefresh: () async {
        liveCount = 30;
        await getMatchDetail();
      },
      onLoad: nomore
          ? null
          : () async {
              liveCount += 30;
              update();
            },
      childBuilder: (ctx, b) => MediaQuery.removePadding(
        context: ctx,
        removeTop: true,
        child: CustomScrollView(
          physics: b,
          slivers: [
            const SliverToBoxAdapter(
              child: AdsLabel(
                adsTag: "match_lq_赛况",
                tapType: 'ggw_bsxq_zb',
                margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
              ),
            ),
            LoadingWidget<bool>(
              isLoading: false,
              data: detail?.appMatchTlives?.hasValue != true,
              noData: NoDataWidget.sliver(tip: "暂无数据", physics: b),
              child: () => SliverToBoxAdapter(
                child: Styles.card(
                  margin: const EdgeInsets.all(8),
                  radius: 8,
                  child: Column(children: [_liveTextBox(), _vSpace()])
                ).paddingOnly(bottom: 50),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _vSpace() => const SizedBox(height: 10);

  Widget logo(String url, {double size = 24}) {
    return Container(
        width: size,
        height: size,
        decoration: const BoxDecoration(shape: BoxShape.circle),
        child: CachedNetworkImage(
            imageUrl: url,
            placeholder: (context, url) => Styles.placeholderIcon(),
            errorWidget: (context, url, error) => Image.asset(
                  Utils.getImgPath('lq_placeholder.png'),
                  width: size,
                  height: size,
                )));
  }

  Widget _homeLogo({double size = 24}) =>
      logo(detail?.homeTeamLogo ?? "", size: size);
  Widget _awayLogo({double size = 24}) =>
      logo(detail?.awayTeamLogo ?? "", size: size);

  Widget _liveTextCell(DetailMatchLiveTextDataEntity e, String t, bool islast) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 30,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  if(e.teamType == 0)...[
                    Image.asset(Utils.getImgPath("text_live_host.png"),width: 24)
                  ]else...[
                    e.teamType == 1 ? _homeLogo() : _awayLogo()
                  ],
                  if (!islast)
                    Expanded(
                        child: Container(
                      width: 0.5,
                      color: const Color(0xffd7d7d7),
                    ))
                ],
              ),
            ),
            const SizedBox(
              width: 6,
            ),
            Expanded(
              child: Column(
                children: [
                  DefaultTextStyle(
                    style: const TextStyle(fontSize: 12, color: Colours.grey99),
                    child: Row(
                      children: [
                        QkdText("$t ${e.time ?? ""}"),
                        const Spacer(),
                        QkdText(e.scores ?? "-")
                      ],
                    ).paddingSymmetric(vertical: 2),
                  ),
                  const SizedBox(
                    height: 2,
                  ),
                  Container(
                    alignment: Alignment.topLeft,
                    padding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
                    decoration: BoxDecoration(
                        color: Colours.greyF7,
                        borderRadius: BorderRadius.circular(8)),
                    child: QkdText(e.data ?? "-"),
                  ),
                  const SizedBox(height: 10)
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget switchBtns(List<DetailMatchLiveTextEntity> lives1) => Container(
        margin: const EdgeInsets.only(left: 12, right: 12, top: 16),
        height: 37,
        decoration: BoxDecoration(
            color: Colours.greyF7, borderRadius: BorderRadius.circular(33.5)),
        child: Stack(
          children: [
            Positioned.fill(child: LayoutBuilder(
              builder: (context, cons) {
                final count = lives1.isEmpty ? 1 : lives1.length;
                final width = (cons.maxWidth - 4) / count;
                return Row(
                  children: [
                    AnimatedContainer(
                        width: 2 + (periodNum - 1) * width,
                        duration: const Duration(milliseconds: 200)),
                    Container(
                      width: lives1.isEmpty ? 0 : cons.maxWidth / lives1.length,
                      height: 33,
                      decoration: BoxDecoration(
                          color: Colours.white,
                          borderRadius: BorderRadius.circular(33.5)),
                    )
                  ],
                );
              },
            )),
            Row(
              children: [
                ...List.generate(lives1.length, (index) {
                  final p = index + 1;
                  return Expanded(
                    child: Container(
                      // color: p == periodNum ? Colors.white : null,
                      height: 36,
                      alignment: Alignment.center,
                      child: QkdText(
                        lives1[index].name ?? "",
                        color:
                        p == periodNum ? Colours.main : Colours.grey66,
                        fontWeight:
                        p == periodNum ? FontWeight.w500 : null,
                      ),
                    ).tap(() {
                      periodNum = p;
                      liveCount = 30;
                      update();
                    }),
                  );
                })
              ],
            ),
          ],
        ),
      );

  Widget _liveTextBox() {
    final lives1 = detail?.appMatchTlives;
    if (lives1?.isEmpty ?? true) {
      log('lives empty ${detail?.appMatchTlives}');
      return const NoDataWidget(tip: "暂无数据").sized(height: 450);
    }
    final count2 = nomore ? lives.length : liveCount;
    final list = lives.sublist(0, count2);
    final t = lives1?[periodNum - 1].name ?? "";
    return Column(
      children: [
        switchBtns(lives1 ?? []),
        list.isEmpty
            ? const NoDataWidget()
            : Container(
                color: Colors.white,
                child: Column(
                  children: [
                    const SizedBox(height: 12),
                    ...List.generate(list.length, (index) {
                      bool islast = list.length == index + 1;
                      return _liveTextCell(list[index], t, islast);
                    }),
                    if (list.isEmpty) const NoDataWidget(),
                  ],
                ),
              ),
      ],
    );
  }
}
